package com.mdinfo.gw.device.websocket.endpoint;

import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by Administrator on 2017/12/18.
 */
@ServerEndpoint("/myAlarm")
@Service
public class AlarmEndPoint {

    private static Map<String,Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session){
        System.out.println("新连接:"+session.getId());
        sessionMap.put(session.getId(),session);
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("关闭:"+session.getId());
        sessionMap.remove(session.getId());

        if(session.isOpen()){
            System.out.println("session存活");
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("session已经被关闭了");
        }

        if(session.isOpen()){
            System.out.println("还活着");
        }else{
            System.out.println("这次死了");
        }

    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("收到消息:"+message);
        sendMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误:"+session.getId());
        sessionMap.remove(session.getId());
        error.printStackTrace();
    }

    public static void sendMessage(String message){

        sessionMap.forEach((key,session)->{
            if(session.isOpen()){
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
